﻿using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using GL = UnityEngine.GUILayout;
using EGL = UnityEditor.EditorGUILayout;

namespace UFrame
{
    /// <summary>
    /// 查看游戏存档信息界面
    /// </summary>
    public class PlayerPrefsCheckWindow : EditorWindow
    {
        public static List<string> classSaveName = new  List<string>();
        
        public enum PrefType
        {
            Int,
            String,
            Float,
        }

        public class PreTypeEntity
        {
            public string name;
            public PrefType type;
            public string valStr = "";
            public float valFloat = 0f;
            public int valInt = 0;

            public float checkTime = 1f;
            public bool hasValue = false;
        }

        public Dictionary<string, string> allProperty = new Dictionary<string, string>();
        public Dictionary<string, PreTypeEntity> propertyDic = new Dictionary<string, PreTypeEntity>();

        public string id = "";
        public string value = "";
        public PrefType valType = PrefType.Int;

        [MenuItem("Plateface/ORM/PlayerCheck")]
        public static void OpenPlayerPrefsCheck()
        {
            PlayerPrefsCheckWindow myWindow = GetWindow<PlayerPrefsCheckWindow>("小游戏存档", true);

            Analysis(myWindow);
            //myWindow.mSize = new Vector2(600,800);

            myWindow.Show();
        }


        public static void Analysis(PlayerPrefsCheckWindow myWindow)
        {
            myWindow.allProperty.Clear();

            var configVar = Resources.Load<TextAsset>("ConfigVar");
            if (configVar == null)
            {
                Debug.LogError("Resources文件夹下没有存在ConfigVar");
                return;
            }

            string[] lines = configVar.text.Split(new string[] {"\r\n"}, StringSplitOptions.None);
            foreach (var item in lines)
            {
                var itemAry = item.Split(' ');
                if (string.IsNullOrEmpty(itemAry[0]))
                {
                    continue;
                }

                if (string.IsNullOrEmpty(itemAry[1]))
                {
                    continue;
                }

                if (itemAry.Length > 2)
                {
                    if (itemAry[2].Contains("-"))
                    {
                        var numberAry = itemAry[2].Split('-');
                        int startIndex = Convert.ToInt32(numberAry[0]);
                        int endIndex = Convert.ToInt32(numberAry[1]);

                        for (int i = startIndex; i < endIndex; i++)
                        {
                            myWindow.allProperty.Add(itemAry[1].Trim() + i, itemAry[0].Trim());        
                        }
                        continue;
                    }
                }
                myWindow.allProperty.Add(itemAry[1].Trim(), itemAry[0].Trim());
            }


            myWindow.Init(myWindow.allProperty);
        }

        public void OnFocus()
        {
            Analysis(this);
            this.name = "小游戏存档设置";
            this.minSize = new Vector2(600, 200);
        }

        public void OnSelectionChange()
        {
            this.name = "小游戏存档设置";
            this.minSize = new Vector2(600, 200);
        }

        public void Awake()
        {
            this.name = "小游戏存档设置";
            this.minSize = new Vector2(600, 200);
        }

        public void Reset()
        {
            Analysis(this);
            
            this.name = "小游戏存档设置";
            this.minSize = new Vector2(600, 200);
        }

        public void OnEnable()
        {
            this.name = "小游戏存档设置";
            this.minSize = new Vector2(600, 200);
        }


        public void Init(Dictionary<string, string> allProperty)
        {
            propertyDic.Clear();
            var sc = StringComparison.OrdinalIgnoreCase;
            foreach (var item in allProperty)
            {
                PreTypeEntity e = new PreTypeEntity();
                propertyDic.Add(item.Key, e);
                e.name = item.Key;
                e.type = Get(item.Value);

                if (PlayerPrefs.HasKey(e.name))
                {
                    if (e.type == PrefType.String)
                        e.valStr = PlayerPrefs.GetString(e.name, "");
                    if (e.type == PrefType.Float)
                        e.valFloat = PlayerPrefs.GetFloat(e.name, 0f);
                    if (e.type == PrefType.Int)
                        e.valInt = PlayerPrefs.GetInt(e.name, 0);
                }
                else
                {
                }
            }
        }

        public PrefType Get(string name)
        {
            var sc = StringComparison.OrdinalIgnoreCase;
            if (name.Equals("int", sc))
            {
                return PrefType.Int;
            }
            else if (name.Equals("float", sc))
            {
                return PrefType.Float;
            }
            else
            {
                return PrefType.String;
            }
        }

        public void SetValue(PreTypeEntity entity)
        {
            if (entity.type == PrefType.Float)
            {
                PlayerPrefs.SetFloat(entity.name, entity.valFloat);
            }
            else if (entity.type == PrefType.Int)
            {
                PlayerPrefs.SetInt(entity.name, entity.valInt);
            }
            else
            {
                PlayerPrefs.SetString(entity.name, entity.valStr);
            }
        }

        public void ReadValue(PreTypeEntity entity)
        {
            var type = entity.type;
            var name = entity.name;

            if (type == PrefType.String)
                entity.valStr = PlayerPrefs.GetString(name, "");
            if (type == PrefType.Float)
                entity.valFloat = PlayerPrefs.GetFloat(name, 0f);
            if (type == PrefType.Int)
                entity.valInt = PlayerPrefs.GetInt(name, 0);
        }


        public void OnGUI()
        {
            ListKeyUI();
            AddKeyUI();
        }

        private float scrollPos = 0f;
        private Vector2 v = new Vector2(0,0);
        public void ListKeyUI()
        {
            v = EGL.BeginScrollView(v);
            foreach (var item in propertyDic)
            {
                GL.BeginHorizontal();
                var entity = item.Value;
                GL.Label(entity.name, GL.Width(150));


                if (Time.realtimeSinceStartup - entity.checkTime >= 1f)
                {
                    if (PlayerPrefs.HasKey(entity.name))
                    {
                        entity.hasValue = true;
                        entity.checkTime = 0;
                    }
                    else
                    {
                        entity.hasValue = false;
                        entity.checkTime = 0;
                    }
                }

                if (entity.hasValue)
                {
                    GL.Label("有", GL.Width(30));
                }
                else
                {
                    GL.Label("无", GL.Width(30));
                }

                entity.type = (PrefType) EGL.EnumPopup(entity.type, GL.Width(100));

                if (item.Value.type == PrefType.Int)
                {
                    entity.valInt = EGL.IntField(entity.valInt);
                }
                else if (item.Value.type == PrefType.Float)
                {
                    entity.valFloat = EGL.FloatField(entity.valFloat);
                }
                else
                {
                    entity.valStr = EGL.TextField(entity.valStr);
                }

                if (GL.Button("设置值"))
                {
                    SetValue(entity);
                }

                if (GL.Button("重新读取"))
                {
                    ReadValue(entity);
                }

                if (GL.Button("删除"))
                {
                    entity.valFloat = 0f;
                    entity.valInt = 0;
                    entity.valStr = "";
                    entity.hasValue = false;
                    PlayerPrefs.DeleteKey(entity.name);
                }

                GL.EndHorizontal();
            }
            EGL.EndScrollView();
        }

        public void AddKeyUI()
        {
            GL.Space(50);
            GL.Height(300);
            GL.Label("添加值区域");
            //GL.BeginHorizontal();
            EGL.BeginHorizontal("添加值");
            id = EGL.TextField("ID", id);
            value = EGL.TextField("值", value);
            valType = (PrefType) EGL.EnumPopup(valType);
            if (GL.Button("添加"))
            {
                if (valType == PrefType.Float)
                {
                    PlayerPrefs.SetFloat(id, Convert.ToSingle(value));
                }

                if (valType == PrefType.Int)
                {
                    PlayerPrefs.SetInt(id, Convert.ToInt32(value));
                }

                if (valType == PrefType.Float)
                {
                    PlayerPrefs.SetString(id, Convert.ToString(value));
                }

                //添加到集合中
                PreTypeEntity pty = new PreTypeEntity();
                pty.name = id;
                pty.type = valType;
                pty.hasValue = true;
                pty.checkTime = 0f;
                //pty.valFloat
                propertyDic.Add(pty.name, pty);
            }
            EGL.EndHorizontal();

            EGL.BeginHorizontal("添加值");
            if (GUILayout.Button("重新读取",GUILayout.Height(60)))
            {
                foreach (var className in classSaveName)
                {
                    Type type =  AssemblyTool.SearchType(className); 
                    dynamic obj = type.Assembly.CreateInstance(className);
                    if (obj == null)
                    {
                        Debug.LogError("没有找到类:  " + className);
                    }
                    else
                    {
                        obj.Load();
                    }
                }
            }
            if (GUILayout.Button("删除全部",GUILayout.Height(60)))
            {
                PlayerPrefs.DeleteAll();
            }
            EGL.EndHorizontal();
         

        }
    }
}